import { http } from '@kit.NetworkKit'

let request = http.createHttp()

export function get<T>(url:string, params?:Object):Promise<T> {
  return new Promise<T>((resolve, reject) => {
    if(params) {
      url += "?" + Object.keys(params).map((k) => `${k}=${params[k]}`).join('&')
    }
    request.request(url, {
      method:http.RequestMethod.GET
    })
      .then((r) => {
        if (r.responseCode == 200) {
          resolve(JSON.parse(r.result as string))
        } else {
          reject(new Error(`网络错误: ${r.responseCode}}`))
        }
      })
      .catch((e:Error) => {
        reject(e)
      })
  })
}
export function post<T>(url:string, params?:Object):Promise<T> {
  return new Promise<T>((resolve, reject) => {
    request.request(url, {
      method:http.RequestMethod.POST,
      header: {'Content-Type':'application/json'},
      extraData: params
    })
      .then((r) => {
        if (r.responseCode == 200) {
          resolve(JSON.parse(r.result as string))
        } else {
          reject(new Error(`网络错误: ${r.responseCode}}`))
        }
      })
      .catch((e:Error) => {
        reject(e)
      })
  })
}
